package com.kuhyygy.adapter;

import java.util.List;

import com.kuhyygy.R;
import com.kuhyygy.bean.Msg;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MsgAdapter extends ArrayAdapter<Msg> {
	
	private int resourceId;

	public MsgAdapter(Context context, int textViewResourceId, List<Msg> objects) {
		super(context, textViewResourceId, objects);
		this.resourceId = textViewResourceId;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		Msg msg = getItem(position);
		View view;
		ViewHolder viewHolder;
		
		// 初始化View和ViewHolder
		if (null == convertView) {
			view = LayoutInflater.from(getContext()).inflate(resourceId, null);
			viewHolder = new ViewHolder();
			viewHolder.leftLayout = (LinearLayout) view.findViewById(R.id.leftChat);
			viewHolder.rightLayout = (LinearLayout) view.findViewById(R.id.rightChat);
			viewHolder.leftTextView = (TextView) view.findViewById(R.id.leftMsgText);
			viewHolder.rightTextView = (TextView) view.findViewById(R.id.rightMsgText);
			view.setTag(viewHolder);
		} else {
			view = convertView;
			viewHolder = (ViewHolder) view.getTag();
		}
		
		// 设置Msg
		if (msg.getType() == Msg.TYPE_RECEIVED) {
			viewHolder.leftLayout.setVisibility(View.VISIBLE);
			viewHolder.rightLayout.setVisibility(View.GONE);
			viewHolder.leftTextView.setText(msg.getText());
		} else {
			viewHolder.rightLayout.setVisibility(View.VISIBLE);
			viewHolder.leftLayout.setVisibility(View.GONE);
			viewHolder.rightTextView.setText(msg.getText());
		}
		return view;
	}
	
	public int getResourceId() {
		return resourceId;
	}

	public void setResourceId(int resourceId) {
		this.resourceId = resourceId;
	}



	class ViewHolder {
		private LinearLayout leftLayout;
		private LinearLayout rightLayout;
		private TextView leftTextView;
		private TextView rightTextView;
		public LinearLayout getLeftLayout() {
			return leftLayout;
		}
		public void setLeftLayout(LinearLayout leftLayout) {
			this.leftLayout = leftLayout;
		}
		public LinearLayout getRightLayout() {
			return rightLayout;
		}
		public void setRightLayout(LinearLayout rightLayout) {
			this.rightLayout = rightLayout;
		}
		public TextView getLeftTextView() {
			return leftTextView;
		}
		public void setLeftTextView(TextView leftTextView) {
			this.leftTextView = leftTextView;
		}
		public TextView getRightTextView() {
			return rightTextView;
		}
		public void setRightTextView(TextView rightTextView) {
			this.rightTextView = rightTextView;
		}
		
	}
}
